<!DOCTYPE html>













<html class="theme-next gemini" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">










  <meta name="google-site-verification" content="true">







  <meta name="baidu-site-verification" content="true">



  
  
  <link rel="stylesheet" href="/lib/fancybox/source/jquery.fancybox.css">







<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.ico?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.ico?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: true,
    fastclick: false,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="前言保证数据的安全性是继可用性之后最为重要的一项工作，防火墙技术作为公网与内网之间的保护屏障，起着至关重要的作用。面对同学们普遍不了解在红帽RHEL7系统中新旧两款防火墙的差异，刘遄老师决定先带领读者正确的认识在红帽RHEL7系统中firewalld防火墙服务与iptables防火墙服务之间的关系，从理论和事实层面剖析真相。本章节内将会分别使用iptables、firewall-cmd、fir">
<meta name="keywords" content="linux,网络,防火墙">
<meta property="og:type" content="article">
<meta property="og:title" content="iptables和firewalled的区别">
<meta property="og:url" content="https://melville.club/posts/a-2018-10-23-10-15-57.html">
<meta property="og:site_name" content="Melville&#39;s blog">
<meta property="og:description" content="前言保证数据的安全性是继可用性之后最为重要的一项工作，防火墙技术作为公网与内网之间的保护屏障，起着至关重要的作用。面对同学们普遍不了解在红帽RHEL7系统中新旧两款防火墙的差异，刘遄老师决定先带领读者正确的认识在红帽RHEL7系统中firewalld防火墙服务与iptables防火墙服务之间的关系，从理论和事实层面剖析真相。本章节内将会分别使用iptables、firewall-cmd、fir">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E9%98%B2%E7%81%AB%E5%A2%99%E6%8B%93%E6%89%91.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/firewall-config%E7%95%8C%E9%9D%A2.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E5%85%81%E8%AE%B8%E5%85%B6%E4%BB%96%E4%B8%BB%E6%9C%BA%E8%AE%BF%E9%97%AEhttp%E6%9C%8D%E5%8A%A1.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E5%85%81%E8%AE%B8%E5%85%B6%E4%BB%96%E4%B8%BB%E6%9C%BA%E8%AE%BF%E9%97%AE8080-8088%E7%AB%AF%E5%8F%A3.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E9%87%8D%E5%90%AF%E5%90%8E%E4%BE%9D%E7%84%B6%E6%9C%89%E6%95%88.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E6%9C%AA%E7%94%A8SNAT1.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E4%BD%BF%E7%94%A8SNAT1.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E5%BC%80%E5%90%AF%E4%BC%AA%E8%A3%85%E5%8A%9F%E8%83%BD.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E5%B0%86%E5%90%91%E6%9C%AC%E6%9C%BA888%E7%AB%AF%E5%8F%A3%E7%9A%84%E8%AF%B7%E6%B1%82%E8%BD%AC%E5%8F%91%E8%87%B3%E6%9C%AC%E6%9C%BA%E7%9A%8422%E7%AB%AF%E5%8F%A3.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/reload%E7%AB%8B%E5%8D%B3%E7%94%9F%E6%95%88.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E4%BB%85%E5%85%81%E8%AE%B8192.168.10.20%E4%B8%BB%E6%9C%BA%E8%AE%BF%E9%97%AE%E6%9C%AC%E6%9C%BA%E7%9A%841234%E7%AB%AF%E5%8F%A3.png">
<meta property="og:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E6%9F%A5%E7%9C%8B%E7%BD%91%E5%8D%A1%E8%AE%BE%E5%A4%87%E4%BF%A1%E6%81%AF.png">
<meta property="og:updated_time" content="2019-06-13T08:03:09.917Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iptables和firewalled的区别">
<meta name="twitter:description" content="前言保证数据的安全性是继可用性之后最为重要的一项工作，防火墙技术作为公网与内网之间的保护屏障，起着至关重要的作用。面对同学们普遍不了解在红帽RHEL7系统中新旧两款防火墙的差异，刘遄老师决定先带领读者正确的认识在红帽RHEL7系统中firewalld防火墙服务与iptables防火墙服务之间的关系，从理论和事实层面剖析真相。本章节内将会分别使用iptables、firewall-cmd、fir">
<meta name="twitter:image" content="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E9%98%B2%E7%81%AB%E5%A2%99%E6%8B%93%E6%89%91.png">



  <link rel="alternate" href="/atom.xml" title="Melville's blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://melville.club/posts/a-2018-10-23-10-15-57">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>iptables和firewalled的区别 | Melville's blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Melville's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">业精于勤，荒于嬉</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    
      
    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签<span class="badge">38</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类<span class="badge">13</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档<span class="badge">20</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-milestone">

    
    
    
      
    

    
      
    

    <a href="/milestone/" rel="section"><i class="menu-item-icon fa fa-fw fa-flag-checkered"></i> <br>里程碑</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-message">

    
    
    
      
    

    
      
    

    <a href="/message/" rel="section"><i class="menu-item-icon fa fa-fw fa-list-alt"></i> <br>留言板</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-commonweal">

    
    
    
      
    

    
      
    

    <a href="/404/" rel="section"><i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>公益 404</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    
  
  

  

  <a href="https://github.com/do-do-do" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="external nofollow noopener noreferrer" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://melville.club/posts/a-2018-10-23-10-15-57.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Melville">
      <meta itemprop="description" content="改革春风吹满地">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Melville's blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">iptables和firewalled的区别

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-10-23 10:15:57" itemprop="dateCreated datePublished" datetime="2018-10-23T10:15:57+08:00">2018-10-23</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-06-13 16:03:09" itemprop="dateModified" datetime="2019-06-13T16:03:09+08:00">2019-06-13</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/Linux系统/" itemprop="url" rel="index"><span itemprop="name">Linux系统</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/posts/a-2018-10-23-10-15-57.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/posts/a-2018-10-23-10-15-57.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon">
            <i class="fa fa-heart"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <script type="text/javascript" src="/js/src/baidu.js"></script>

<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>保证数据的安全性是继可用性之后最为重要的一项工作，防火墙技术作为公网与内网之间的保护屏障，起着至关重要的作用。面对同学们普遍不了解在红帽RHEL7系统中新旧两款防火墙的差异，刘遄老师决定先带领读者正确的认识在红帽RHEL7系统中firewalld防火墙服务与iptables防火墙服务之间的关系，从理论和事实层面剖析真相。<br>本章节内将会分别使用iptables、firewall-cmd、firewall-config和Tcp_wrappers等防火墙策略配置服务来完成数十个根据真实工作需求而设计的防火墙策略配置实验，让同学们不仅能够熟练的对请求数据包流量进行过滤，还能够基于服务程序进行允许和关闭操作，做到保证Linux系统安全万无一失。</p>
<a id="more"></a>
<h1 id="1-防火墙管理工具"><a href="#1-防火墙管理工具" class="headerlink" title="1. 防火墙管理工具"></a>1. 防火墙管理工具</h1><p>保证数据的安全性是继可用性之后最为重要的一项工作，众所周知外部公网相比企业内网更加的“罪恶丛生”，因此防火墙技术作为公网与内网之间的保护屏障，虽然有软件或硬件之分，但主要功能都是依据策略对外部请求进行过滤。防火墙技术能够做到监控每一个数据包并判断是否有相应的匹配策略规则，直到匹配到其中一条策略规则或执行默认策略为止，防火墙策略可以基于来源地址、请求动作或协议等信息来定制，最终仅让合法的用户请求流入到内网中，其余的均被丢弃。</p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E9%98%B2%E7%81%AB%E5%A2%99%E6%8B%93%E6%89%91.png" width="50%" height="50%"></p>
<p>在红帽RHEL7系统中Firewalld服务取代了Iptables服务，对于接触Linux系统比较早或学习过红帽RHEL6系统的读者来讲，突然改用Firewalld服务后确实不免会有些抵触心理，或许会觉得Firewalld服务是一次不小的改变。但其实Iptables服务与Firewalld服务都不是真正的防火墙，它们都只是用来定义防火墙策略功能的“防火墙管理工具”而已，iptables服务会把配置好的防火墙策略交由内核层面的netfilter网络过滤器来处理，而firewalld服务则是把配置好的防火墙策略交由内核层面的nftables包过滤框架来处理。换句话说，当前在Linux系统中其实同时有多个防火墙管理工具共同存在，它们的作用都是为了方便运维人员管理Linux系统的防火墙策略，而咱们只要配置妥当其中一个就足够了。虽然各个工具之间各有优劣特色，但对于防火墙策略的配置思路上是保持一致的，同学们甚至可以不用完全掌握本章节内的知识，而是在这诸多个防火墙管理工具中任选一款来学透即可，完全能够满足日常的工作所需。</p>
<h1 id="2-iptables"><a href="#2-iptables" class="headerlink" title="2. iptables"></a>2. iptables</h1><p>在较早期的Linux系统中想配置防火墙默认使用的都是iptables防火墙管理命令，而新型Firewalld防火墙管理服务已经被投入使用多年，但还记得刘遄老师在第0章0.6小节里谈到过企业不愿意及时升级的原因吧，于是不论出于什么样的原因，目前市场上还有大量的生产环境中在使用着iptables命令来管理着防火墙的规则策略。虽然明知iptables可能有着即将被“淘汰”的命运，但为了让同学们不必在面试时尴尬以及看完手中这本《Linux就该这么学》书籍后能“通吃”各个版本的Linux系统，刘遄老师觉得还是有必要把这一项技术好好卖力气讲一下，更何况各个工具的配置防火墙策略思路上大体一致，具有很高的相同性及借鉴意义。</p>
<h2 id="2-1-策略与规则链"><a href="#2-1-策略与规则链" class="headerlink" title="2.1 策略与规则链"></a>2.1 策略与规则链</h2><p>防火墙会从上至下来读取规则策略，一旦匹配到了合适的就会去执行并立即结束匹配工作，但也有转了一圈之后发现没有匹配到合适规则的时候，那么就会去执行默认的策略。因此对防火墙策略的设置无非有两种，一种是“通”，一种是“堵”——当防火墙的默认策略是拒绝的，就要设置允许规则，否则谁都进不来了，而如果防火墙的默认策略是允许的，就要设置拒绝规则，否则谁都能进来了，起不到防范的作用。</p>
<p>iptables命令把对数据进行过滤或处理数据包的策略叫做规则，把多条规则又存放到一个规则链中，规则链是依据处理数据包位置的不同而进行的分类，包括有：在进行路由选择前处理数据包（PREROUTING）、处理流入的数据包（INPUT）、处理流出的数据包（OUTPUT）、处理转发的数据包（FORWARD）、在进行路由选择后处理数据包（POSTROUTING）。从内网向外网发送的数据一般都是可控且良性的，因此显而易见咱们使用最多的就是INPUT数据链，这个链中定义的规则起到了保证私网设施不受外网骇客侵犯的作用。</p>
<p>比如您所居住的社区物业保安有两条规定——“禁止小商贩进入社区，各种车辆都需要登记”，这两条安保规定很明显应该是作用到了社区的正门（流量必须经过的地方），而不是每家每户的防盗门上。根据前面提到的防火墙策略的匹配顺序规则，咱们可以猜想有多种情况——比如来访人员是小商贩，则会被物业保安直接拒绝在大门外，也无需再对车辆进行登记，而如果来访人员是一辆汽车，那么因为第一条禁止小商贩策略就没有被匹配到，因而按顺序匹配到第二条策略，需要对车辆进行登记，再有如果来访的是社区居民，则既不满足小商贩策略，也不满足车辆登记策略，因此会执行默认的放行策略。</p>
<p>不过只有规则策略还不能保证社区的安全，物业保安还应该知道该怎么样处理这些被匹配到的流量，比如包括有“允许”、“登记”、“拒绝”、“不理他”，这些动作对应到iptables命令术语中是ACCEPT（允许流量通过）、LOG（记录日志信息）、REJECT（拒绝流量通过）、DROP（拒绝流量通过）。允许动作和记录日志工作都比较好理解，着重需要讲解的是这两条拒绝动作的不同点，其中REJECT和DROP的动作操作都是把数据包拒绝，DROP是直接把数据包抛弃不响应，而REJECT会拒绝后再回复一条“您的信息我已收到，但被扔掉了”，让对方清晰的看到数据被拒绝的响应。就好比说您有一天正在家里看电视，突然有人敲门，透过“猫眼”一看是推销商品的，咱们如果不需要的情况下就会直接拒绝他们（REJECT）。但如果透过“猫眼”看到的是债主带了几十个小弟来讨债，这种情况不光要拒绝开门，还要默不作声，伪装成自己不在家的样子（DROP），这就是两种拒绝动作的不同之处。</p>
<p>把Linux系统设置成REJECT拒绝动作策略后，对方会看到本机的端口不可达的响应：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># ping -c 4 192.168.10.10</span></span><br><span class="line">PING 192.168.10.10 (192.168.10.10) 56(84) bytes of data.</span><br><span class="line">From 192.168.10.10 icmp_seq=1 Destination Port Unreachable</span><br><span class="line">From 192.168.10.10 icmp_seq=2 Destination Port Unreachable</span><br><span class="line">From 192.168.10.10 icmp_seq=3 Destination Port Unreachable</span><br><span class="line">From 192.168.10.10 icmp_seq=4 Destination Port Unreachable</span><br><span class="line">--- 192.168.10.10 ping statistics ---</span><br><span class="line">4 packets transmitted, 0 received, +4 errors, 100% packet loss, time 3002ms</span><br></pre></td></tr></table></figure>
<p>把Linux系统设置成DROP拒绝动作策略后，对方会看到本机响应超时的提醒，无法判断流量是被拒绝，还是对方主机当前不在线：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># ping -c 4 192.168.10.10</span></span><br><span class="line">PING 192.168.10.10 (192.168.10.10) 56(84) bytes of data.</span><br><span class="line"></span><br><span class="line">--- 192.168.10.10 ping statistics ---</span><br><span class="line">4 packets transmitted, 0 received, 100% packet loss, time 3000ms</span><br></pre></td></tr></table></figure>
<h2 id="2-2-基本的命令参数"><a href="#2-2-基本的命令参数" class="headerlink" title="2.2 基本的命令参数"></a>2.2 基本的命令参数</h2><p>iptables是一款基于命令行的防火墙策略管理工具，由于该命令是基于终端执行且存在有大量参数的，学习起来难度还是较大的，好在对于日常控制防火墙策略来讲，您无需深入的了解诸如“四表五链”的理论概念，只需要掌握常用的参数并做到灵活搭配即可，以便于能够更顺畅的胜任工作所需。iptables命令可以根据数据流量的源地址、目的地址、传输协议、服务类型等等信息项进行匹配，一旦数据包与策略匹配上后，iptables就会根据策略所预设的动作来处理这些数据包流量，另外再来提醒下同学们防火墙策略的匹配顺序规则是从上至下的，因此切记要把较为严格、优先级较高的策略放到靠前位置，否则有可能产生错误。下表中为读者们总结归纳了几乎所有常用的iptables命令参数，刘遄老师遵循《Linux就该这么学》书籍的编写初衷而设计了大量动手实验，让您无需生背硬记这些参数，可以结合下面的实例来逐个参阅即可。</p>
<table>
<thead>
<tr>
<th style="text-align:left">参数</th>
<th style="text-align:left">作用</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">-P</td>
<td style="text-align:left">设置默认策略:iptables -P INPUT (DROP&#124;ACCEPT)</td>
</tr>
<tr>
<td style="text-align:left">-F</td>
<td style="text-align:left">清空规则链</td>
</tr>
<tr>
<td style="text-align:left">-L</td>
<td style="text-align:left">查看规则链</td>
</tr>
<tr>
<td style="text-align:left">-A</td>
<td style="text-align:left">在规则链的末尾加入新规则</td>
</tr>
<tr>
<td style="text-align:left">-I num</td>
<td style="text-align:left">在规则链的头部加入新规则</td>
</tr>
<tr>
<td style="text-align:left">-D num</td>
<td style="text-align:left">删除某一条规则</td>
</tr>
<tr>
<td style="text-align:left">-s</td>
<td style="text-align:left">匹配来源地址IP/MASK，加叹号”!”表示除这个IP外。</td>
</tr>
<tr>
<td style="text-align:left">-d</td>
<td style="text-align:left">匹配目标地址</td>
</tr>
<tr>
<td style="text-align:left">-i 网卡名称</td>
<td style="text-align:left">匹配从这块网卡流入的数据</td>
</tr>
<tr>
<td style="text-align:left">-o 网卡名称</td>
<td style="text-align:left">匹配从这块网卡流出的数据</td>
</tr>
<tr>
<td style="text-align:left">-p</td>
<td style="text-align:left">匹配协议,如tcp,udp,icmp</td>
</tr>
<tr>
<td style="text-align:left">–dport num</td>
<td style="text-align:left">匹配目标端口号</td>
</tr>
<tr>
<td style="text-align:left">–sport num</td>
<td style="text-align:left">匹配来源端口号</td>
</tr>
<tr>
<td style="text-align:left">-j</td>
<td style="text-align:left">指定动作类型</td>
</tr>
</tbody>
</table>
<p>使用iptables命令-L参数查看已有的防火墙策略：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -L</span></span><br><span class="line">Chain INPUT (policy ACCEPT)</span><br><span class="line">target prot opt <span class="built_in">source</span> destination </span><br><span class="line">ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED</span><br><span class="line">ACCEPT all -- anywhere anywhere </span><br><span class="line">INPUT_direct all -- anywhere anywhere </span><br><span class="line">INPUT_ZONES_SOURCE all -- anywhere anywhere </span><br><span class="line">INPUT_ZONES all -- anywhere anywhere </span><br><span class="line">ACCEPT icmp -- anywhere anywhere </span><br><span class="line">REJECT all -- anywhere anywhere reject-with icmp-host-prohibited</span><br><span class="line">………………省略部分输出信息………………</span><br></pre></td></tr></table></figure>
<p>使用iptables命令-F参数清空已有的防火墙策略：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -F</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -L</span></span><br><span class="line">Chain INPUT (policy ACCEPT)</span><br><span class="line">target prot opt <span class="built_in">source</span> destination </span><br><span class="line">………………省略部分输出信息………………</span><br></pre></td></tr></table></figure>
<p>把INPUT链的默认策略设置为拒绝：</p>
<p>如前面所提到的防火墙策略设置无非有两种方式，一种是“通”，一种是“堵”，当把INPUT链设置为默认拒绝后，就要往里面写入允许策略了，否则所有流入的数据包都会被默认拒绝掉，同学们需要留意规则链的默认策略拒绝动作只能是DROP，而不能是REJECT。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -P INPUT DROP</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -L</span></span><br><span class="line">Chain INPUT (policy DROP)</span><br><span class="line">target prot opt <span class="built_in">source</span> destination </span><br><span class="line">…………省略部分输出信息………………</span><br></pre></td></tr></table></figure>
<p>向INPUT链中添加允许icmp数据包流入的允许策略：</p>
<p>在日常运维工作中经常会使用到ping命令来检查对方主机是否在线，而向防火墙INPUT链中添加一条允许icmp协议数据包流入的策略就是默认允许了这种ping命令检测行为。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># ping -c 4 192.168.10.10</span></span><br><span class="line">PING 192.168.10.10 (192.168.10.10) 56(84) bytes of data.</span><br><span class="line"></span><br><span class="line">--- 192.168.10.10 ping statistics ---</span><br><span class="line">4 packets transmitted, 0 received, 100% packet loss, time 3000ms</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -I INPUT -p icmp -j ACCEPT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># ping -c 4 192.168.10.10</span></span><br><span class="line">PING 192.168.10.10 (192.168.10.10) 56(84) bytes of data.</span><br><span class="line">64 bytes from 192.168.10.10: icmp_seq=1 ttl=64 time=0.156 ms</span><br><span class="line">64 bytes from 192.168.10.10: icmp_seq=2 ttl=64 time=0.117 ms</span><br><span class="line">64 bytes from 192.168.10.10: icmp_seq=3 ttl=64 time=0.099 ms</span><br><span class="line">64 bytes from 192.168.10.10: icmp_seq=4 ttl=64 time=0.090 ms</span><br><span class="line">--- 192.168.10.10 ping statistics ---</span><br><span class="line">4 packets transmitted, 4 received, 0% packet loss, time 2999ms</span><br><span class="line">rtt min/avg/max/mdev = 0.090/0.115/0.156/0.027 ms</span><br></pre></td></tr></table></figure>
<p>删除INPUT链中的那条策略，并把默认策略还原为允许：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -D INPUT 1</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -P INPUT ACCEPT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -L</span></span><br><span class="line">Chain INPUT (policy ACCEPT)</span><br><span class="line">target prot opt <span class="built_in">source</span> destination</span><br><span class="line">………………省略部分输出信息………………</span><br></pre></td></tr></table></figure>
<p>设置INPUT链只允许指定网段访问本机的22端口，拒绝其他所有主机的数据请求流量：</p>
<p>防火墙策略是按照从上至下顺序匹配的，因此请一定要记得把允许动作放到拒绝动作上面，否则所有的流量就先被拒绝掉了，任何人都获取不到咱们的业务。文中提到的22端口是下面第9章节讲的ssh服务做占用的资源，刘遄老师在这里挖个小坑~等读者们稍后学完再回来验证这个实验效果吧~</p>
<blockquote>
<p>#屏蔽单个IP的命令是<br>iptables -I INPUT -s 123.45.6.7 -j DROP  </p>
</blockquote>
<blockquote>
<p>#封整个段即从123.0.0.1到123.255.255.254的命令<br>iptables -I INPUT -s 123.0.0.0/8 -j DROP </p>
</blockquote>
<blockquote>
<p>#封IP段即从123.45.0.1到123.45.255.254的命令<br>iptables -I INPUT -s 124.45.0.0/16 -j DROP  </p>
</blockquote>
<blockquote>
<p>#封IP段即从123.45.6.1到123.45.6.254的命令是<br>iptables -I INPUT -s 123.45.6.0/24 -j DROP</p>
</blockquote>
<blockquote>
<p>#指定几个ip123.45.6.0，123.45.6.1,能用ssh连接，其他均不行。<br>iptables -I INPUT -s 123.45.6.0/123.45.6.2 -p tcp -j ACCEPT</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">iptables -A INPUT -p tcp --dport 22 -j REJECT</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -I INPUT -s 192.168.10.0/24 -p tcp --dport 22 -j ACCEPT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -A INPUT -p tcp --dport 22 -j REJECT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -L</span></span><br><span class="line">Chain INPUT (policy ACCEPT)</span><br><span class="line">target prot opt <span class="built_in">source</span> destination </span><br><span class="line">ACCEPT tcp -- 192.168.10.0/24 anywhere tcp dpt:ssh</span><br><span class="line">REJECT tcp -- anywhere anywhere tcp dpt:ssh reject-with icmp-port-unreachable</span><br><span class="line">………………省略部分输出信息………………</span><br></pre></td></tr></table></figure>
<p>使用IP地址在192.168.10.0/24网段内的主机访问服务器的22端口：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">[root@Client A ~]<span class="comment"># ssh 192.168.10.10</span></span><br><span class="line">The authenticity of host <span class="string">'192.168.10.10 (192.168.10.10)'</span> can<span class="string">'t be established.</span></span><br><span class="line"><span class="string">ECDSA key fingerprint is 70:3b:5d:37:96:7b:2e:a5:28:0d:7e:dc:47:6a:fe:5c.</span></span><br><span class="line"><span class="string">Are you sure you want to continue connecting (yes/no)? yes</span></span><br><span class="line"><span class="string">Warning: Permanently added '</span>192.168.10.10<span class="string">' (ECDSA) to the list of known hosts.</span></span><br><span class="line"><span class="string">root@192.168.10.10'</span>s password: </span><br><span class="line">Last login: Sun Feb 12 01:50:25 2017</span><br><span class="line">[root@Client A ~]<span class="comment">#</span></span><br></pre></td></tr></table></figure>
<p>使用IP地址在192.168.20.0/24网段外的主机访问服务器的22端口：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[root@Client B ~]<span class="comment"># ssh 192.168.10.10</span></span><br><span class="line">Connecting to 192.168.10.10:22...</span><br><span class="line">Could not connect to <span class="string">'192.168.10.10'</span> (port 22): Connection failed.</span><br></pre></td></tr></table></figure>
<p>向INPUT链中添加拒绝所有人访问本机12345端口的防火墙策略：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -I INPUT -p tcp --dport 12345 -j REJECT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -I INPUT -p udp --dport 12345 -j REJECT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -L</span></span><br><span class="line">Chain INPUT (policy ACCEPT)</span><br><span class="line">target prot opt <span class="built_in">source</span> destination </span><br><span class="line">REJECT udp -- anywhere anywhere udp dpt:italk reject-with icmp-port-unreachable</span><br><span class="line">REJECT tcp -- anywhere anywhere tcp dpt:italk reject-with icmp-port-unreachable</span><br><span class="line">ACCEPT tcp -- 192.168.10.0/24 anywhere tcp dpt:ssh</span><br><span class="line">REJECT tcp -- anywhere anywhere tcp dpt:ssh reject-with icmp-port-unreachable</span><br><span class="line">………………省略部分输出信息………………</span><br></pre></td></tr></table></figure>
<p>向INPUT链中添加拒绝来自于指定192.168.10.5主机访问本机80端口（web服务）的防火墙策略：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -I INPUT -p tcp -s 192.168.10.5 --dport 80 -j REJECT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -L</span></span><br><span class="line">Chain INPUT (policy ACCEPT)</span><br><span class="line">target prot opt <span class="built_in">source</span> destination </span><br><span class="line">REJECT tcp -- 192.168.10.5 anywhere tcp dpt:http reject-with icmp-port-unreachable</span><br><span class="line">REJECT udp -- anywhere anywhere udp dpt:italk reject-with icmp-port-unreachable</span><br><span class="line">REJECT tcp -- anywhere anywhere tcp dpt:italk reject-with icmp-port-unreachable</span><br><span class="line">ACCEPT tcp -- 192.168.10.0/24 anywhere tcp dpt:ssh</span><br><span class="line">REJECT tcp -- anywhere anywhere tcp dpt:ssh reject-with icmp-port-unreachable</span><br><span class="line">………………省略部分输出信息………………</span><br></pre></td></tr></table></figure>
<p>向INPUT链中添加拒绝所有主机不能访问本机1000至1024端口的防火墙策略：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -A INPUT -p tcp --dport 1000:1024 -j REJECT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -A INPUT -p udp --dport 1000:1024 -j REJECT</span></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># iptables -L</span></span><br><span class="line">Chain INPUT (policy ACCEPT)</span><br><span class="line">target prot opt <span class="built_in">source</span> destination </span><br><span class="line">REJECT tcp -- 192.168.10.5 anywhere tcp dpt:http reject-with icmp-port-unreachable</span><br><span class="line">REJECT udp -- anywhere anywhere udp dpt:italk reject-with icmp-port-unreachable</span><br><span class="line">REJECT tcp -- anywhere anywhere tcp dpt:italk reject-with icmp-port-unreachable</span><br><span class="line">ACCEPT tcp -- 192.168.10.0/24 anywhere tcp dpt:ssh</span><br><span class="line">REJECT tcp -- anywhere anywhere tcp dpt:ssh reject-with icmp-port-unreachable</span><br><span class="line">REJECT tcp -- anywhere anywhere tcp dpts:cadlock2:1024 reject-with icmp-port-unreachable</span><br><span class="line">REJECT udp -- anywhere anywhere udp dpts:cadlock2:1024 reject-with icmp-port-unreachable</span><br><span class="line">………………省略部分输出信息………………</span><br></pre></td></tr></table></figure>
<p>是不是还意犹未尽？但对于iptables防火墙管理命令的学习到此就可以结束了，考虑到以后防火墙的发展趋势，同学们只要能把上面的实例看懂看熟就可以完全搞定日常的iptables防火墙配置工作了。但请特别留意下，iptables命令配置的防火墙规则默认会在下一次重启时失效，所以如果您想让配置的防火墙策略永久的生效下去，还要执行一下保存命令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># service iptables save</span></span><br><span class="line">iptables: Saving firewall rules to /etc/sysconfig/iptables: [ OK ]</span><br></pre></td></tr></table></figure>
<h1 id="3-firewalled"><a href="#3-firewalled" class="headerlink" title="3. firewalled"></a>3. firewalled</h1><p>RHEL7是一个集合多款防火墙管理工具并存的系统，Firewalld动态防火墙管理器服务（Dynamic Firewall Manager of Linux systems）是目前默认的防火墙管理工具，同时拥有命令行终端和图形化界面的配置工具，即使是对Linux命令并不熟悉的同学也能快速入门。相比于传统的防火墙管理工具还支持了动态更新技术并加入了“zone区域”的概念，简单来说就是为用户预先准备了几套防火墙策略集合（策略模板），然后可以根据生产场景的不同而选择合适的策略集合，实现了防火墙策略之间的快速切换。例如咱们有一台笔记本电脑每天都要在办公室、咖啡厅和家里使用，按常理推断最安全的应该是家里的内网，其次是公司办公室，最后是咖啡厅，如果需要在办公室内允许文件共享服务的请求流量、回到家中需要允许所有的服务，而在咖啡店则是除了上网外不允许任何其他请求，这样的需求应该是很常见的，在以前只能频繁的进行手动设置，而现在只需要预设好zone区域集合，然后轻轻点击一下就可以切换过去了上百条策略了，极大的提高了防火墙策略的应用效率，常见的zone区域名称及应用可见下表（默认为public）：</p>
<table>
<thead>
<tr>
<th style="text-align:left">区域</th>
<th style="text-align:left">默认规则策略</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">trusted</td>
<td style="text-align:left">允许所有的数据包。</td>
</tr>
<tr>
<td style="text-align:left">home</td>
<td style="text-align:left">拒绝流入的数据包，除非与输出流量数据包相关或是ssh,mdns,ipp-client,samba-client与dhcpv6-client服务则允许。</td>
</tr>
<tr>
<td style="text-align:left">internal</td>
<td style="text-align:left">等同于home区域</td>
</tr>
<tr>
<td style="text-align:left">work</td>
<td style="text-align:left">拒绝流入的数据包，除非与输出流量数据包相关或是ssh,ipp-client与dhcpv6-client服务则允许。</td>
</tr>
<tr>
<td style="text-align:left">public</td>
<td style="text-align:left">拒绝流入的数据包，除非与输出流量数据包相关或是ssh,dhcpv6-client服务则允许。</td>
</tr>
<tr>
<td style="text-align:left">external</td>
<td style="text-align:left">拒绝流入的数据包，除非与输出流量数据包相关或是ssh服务则允许。</td>
</tr>
<tr>
<td style="text-align:left">dmz</td>
<td style="text-align:left">拒绝流入的数据包，除非与输出流量数据包相关或是ssh服务则允许。</td>
</tr>
<tr>
<td style="text-align:left">block</td>
<td style="text-align:left">拒绝流入的数据包，除非与输出流量数据包相关。</td>
</tr>
<tr>
<td style="text-align:left">drop</td>
<td style="text-align:left">拒绝流入的数据包，除非与输出流量数据包相关。</td>
</tr>
</tbody>
</table>
<h2 id="3-1-终端管理工具"><a href="#3-1-终端管理工具" class="headerlink" title="3.1 终端管理工具"></a>3.1 终端管理工具</h2><p>前面第2章学习Linux命令时刘遄老师提到过的，命令行终端是一种极富效率的工作方式，firewall-cmd命令是Firewalld动态防火墙管理器服务的命令行终端。它的参数一般都是以“长格式”来执行的，但同学们也不用太过于担心，因为红帽RHEL7系统非常酷的支持了部分命令的参数补齐，也正好包括了这条命令，也就是说现在除了能够用Tab键来补齐命令或文件名等等内容，还可以用Tab键来补齐下列长格式参数啦（这点特别的棒）。</p>
<table>
<thead>
<tr>
<th style="text-align:left">参数</th>
<th style="text-align:left">作用</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">–get-default-zone</td>
<td style="text-align:left">查询默认的区域名称。</td>
</tr>
<tr>
<td style="text-align:left">–set-default-zone=&lt;区域名称&gt;</td>
<td style="text-align:left">设置默认的区域，永久生效。</td>
</tr>
<tr>
<td style="text-align:left">–get-zones</td>
<td style="text-align:left">显示可用的区域。</td>
</tr>
<tr>
<td style="text-align:left">–get-services</td>
<td style="text-align:left">显示预先定义的服务。</td>
</tr>
<tr>
<td style="text-align:left">–get-active-zones</td>
<td style="text-align:left">显示当前正在使用的区域与网卡名称。</td>
</tr>
<tr>
<td style="text-align:left">–add-source=</td>
<td style="text-align:left">将来源于此IP或子网的流量导向指定的区域。</td>
</tr>
<tr>
<td style="text-align:left">–remove-source=</td>
<td style="text-align:left">不再将此IP或子网的流量导向某个指定区域。</td>
</tr>
<tr>
<td style="text-align:left">–add-interface=&lt;网卡名称&gt;</td>
<td style="text-align:left">将来自于该网卡的所有流量都导向某个指定区域。</td>
</tr>
<tr>
<td style="text-align:left">–change-interface=&lt;网卡名称&gt;</td>
<td style="text-align:left">将某个网卡与区域做关联。</td>
</tr>
<tr>
<td style="text-align:left">–list-all</td>
<td style="text-align:left">显示当前区域的网卡配置参数，资源，端口以及服务等信息。</td>
</tr>
<tr>
<td style="text-align:left">–list-all-zones</td>
<td style="text-align:left">显示所有区域的网卡配置参数，资源，端口以及服务等信息。</td>
</tr>
<tr>
<td style="text-align:left">–add-service=&lt;服务名&gt;</td>
<td style="text-align:left">设置默认区域允许该服务的流量。</td>
</tr>
<tr>
<td style="text-align:left">–add-port=&lt;端口号/协议&gt;</td>
<td style="text-align:left">允许默认区域允许该端口的流量。</td>
</tr>
<tr>
<td style="text-align:left">–remove-service=&lt;服务名&gt;</td>
<td style="text-align:left">设置默认区域不再允许该服务的流量。</td>
</tr>
<tr>
<td style="text-align:left">–remove-port=&lt;端口号/协议&gt;</td>
<td style="text-align:left">允许默认区域不再允许该端口的流量。</td>
</tr>
<tr>
<td style="text-align:left">–reload</td>
<td style="text-align:left">让“永久生效”的配置规则立即生效，覆盖当前的。</td>
</tr>
<tr>
<td style="text-align:left">–panic-on</td>
<td style="text-align:left">开启应急状况模式。</td>
</tr>
<tr>
<td style="text-align:left">–panic-off</td>
<td style="text-align:left">关闭应急状况模式。</td>
</tr>
</tbody>
</table>
<p>与Linux系统中其他的防火墙策略配置工具一样，使用firewalld配置的防火墙策略默认为运行时（Runtime）模式，又称为当前生效模式，而且随着系统的重启会失效。如果想让配置策略一直存在，就需要使用永久（Permanent）模式了，方法就是在用firewall-cmd命令正常设置防火墙策略时添加–permanent参数，这样配置的防火墙策略就可以永久生效了。但是，永久生效模式有一个“不近人情”的特点，就是使用它设置的策略只有在系统重启之后才能自动生效。如果想让配置的策略立即生效，需要手动执行firewall-cmd –reload命令。</p>
<p>接下来的实验都很简单，但是提醒大家一定要仔细查看刘遄老师使用的是Runtime模式还是Permanent模式。如果不关注这个细节，就算是正确配置了防火墙策略，也可能无法达到预期的效果。</p>
<p>查看firewalld服务当前所使用的区域：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --get-default-zone</span></span><br><span class="line">public</span><br></pre></td></tr></table></figure>
<p>查询eno16777728网卡在firewalld服务中的区域：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --get-zone-of-interface=eno16777728</span></span><br><span class="line">public</span><br></pre></td></tr></table></figure>
<p>把firewalld服务中eno16777728网卡的默认区域修改为external，并在系统重启后生效。分别查看当前与永久模式下的区域名称：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --permanent --zone=external --change-interface=eno16777728</span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --get-zone-of-interface=eno16777728</span></span><br><span class="line">public</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --permanent --get-zone-of-interface=eno16777728</span></span><br><span class="line">external</span><br></pre></td></tr></table></figure>
<p>把firewalld服务的当前默认区域设置为public：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --set-default-zone=public</span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --get-default-zone </span></span><br><span class="line">public</span><br></pre></td></tr></table></figure>
<p>启动/关闭firewalld防火墙服务的应急状况模式，阻断一切网络连接（当远程控制服务器时请慎用）：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --panic-on</span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --panic-off</span></span><br><span class="line">success</span><br></pre></td></tr></table></figure>
<p>查询public区域是否允许请求SSH和HTTPS协议的流量：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --zone=public --query-service=ssh</span></span><br><span class="line">yes</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --zone=public --query-service=https</span></span><br><span class="line">no</span><br></pre></td></tr></table></figure>
<p>把firewalld服务中请求HTTPS协议的流量设置为永久允许，并立即生效：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --zone=public --add-service=https</span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --permanent --zone=public --add-service=https</span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --reload</span></span><br><span class="line">success</span><br></pre></td></tr></table></figure>
<p>把firewalld服务中请求HTTP协议的流量设置为永久拒绝，并立即生效：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --permanent --zone=public --remove-service=http </span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --reload </span></span><br><span class="line">success</span><br></pre></td></tr></table></figure>
<p>把在firewalld服务中访问8080和8081端口的流量策略设置为允许，但仅限当前生效：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --zone=public --add-port=8080-8081/tcp</span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --zone=public --list-ports </span></span><br><span class="line">8080-8081/tcp</span><br></pre></td></tr></table></figure>
<p>把原本访问本机888端口的流量转发到22端口，要且求当前和长期均有效：</p>
<blockquote>
<p>流量转发命令格式为firewall-cmd –permanent –zone=&lt;区域&gt; –add-forward-port=port=&lt;源端口号&gt;:proto=&lt;协议&gt;:toport=&lt;目标端口号&gt;:toaddr=&lt;目标IP地址&gt;</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --permanent --zone=public --add-forward-port=port=888:proto=tcp:toport=22:toaddr=192.168.10.10</span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --reload</span></span><br><span class="line">success</span><br></pre></td></tr></table></figure>
<p>在客户端使用ssh命令尝试访问192.168.10.10主机的888端口：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">[root@client A ~]<span class="comment"># ssh -p 888 192.168.10.10</span></span><br><span class="line">The authenticity of host <span class="string">'[192.168.10.10]:888 ([192.168.10.10]:888)'</span> can<span class="string">'t be established.</span></span><br><span class="line"><span class="string">ECDSA key fingerprint is b8:25:88:89:5c:05:b6:dd:ef:76:63:ff:1a:54:02:1a.</span></span><br><span class="line"><span class="string">Are you sure you want to continue connecting (yes/no)? yes</span></span><br><span class="line"><span class="string">Warning: Permanently added '</span>[192.168.10.10]:888<span class="string">' (ECDSA) to the list of known hosts.</span></span><br><span class="line"><span class="string">root@192.168.10.10'</span>s password:此处输入远程root管理员的密码</span><br><span class="line">Last login: Sun Jul 19 21:43:48 2017 from 192.168.10.10</span><br></pre></td></tr></table></figure>
<p>firewalld中的富规则表示更细致、更详细的防火墙策略配置，它可以针对系统服务、端口号、源地址和目标地址等诸多信息进行更有针对性的策略配置。它的优先级在所有的防火墙策略中也是最高的。比如，我们可以在firewalld服务中配置一条富规则，使其拒绝192.168.10.0/24网段的所有用户访问本机的ssh服务（22端口）：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --permanent --zone=public --add-rich-rule="rule family="ipv4" source address="192.168.10.0/24" service name="ssh" reject"</span></span><br><span class="line">success</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># firewall-cmd --reload</span></span><br><span class="line">success</span><br></pre></td></tr></table></figure>
<p>在客户端使用ssh命令尝试访问192.168.10.10主机的ssh服务（22端口）：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[root@client A ~]<span class="comment"># ssh 192.168.10.10</span></span><br><span class="line">Connecting to 192.168.10.10:22...</span><br><span class="line">Could not connect to <span class="string">'192.168.10.10'</span> (port 22): Connection failed.</span><br></pre></td></tr></table></figure>
<h2 id="3-2-图形管理工具"><a href="#3-2-图形管理工具" class="headerlink" title="3.2 图形管理工具"></a>3.2 图形管理工具</h2><p>在各种版本的Linux系统中，几乎没有能让刘遄老师欣慰并推荐的图形化工具，但是firewall-config做到了。它是firewalld防火墙配置管理工具的GUI（图形用户界面）版本，几乎可以实现所有以命令行来执行的操作。毫不夸张的说，即使读者没有扎实的Linux命令基础，也完全可以通过它来妥善配置RHEL 7中的防火墙策略。firewall-config的界面如图8-2所示，其功能具体如下。</p>
<blockquote>
<p>1：选择运行时（Runtime）模式或永久（Permanent）模式的配置。<br>2：可选的策略集合区域列表。<br>3：常用的系统服务列表。<br>4：当前正在使用的区域。<br>5：管理当前被选中区域中的服务。<br>6：管理当前被选中区域中的端口。<br>7：开启或关闭SNAT（源地址转换协议）技术。<br>8：设置端口转发策略。<br>9：控制请求icmp服务的流量。<br>10：管理防火墙的富规则。<br>11：管理网卡设备。<br>12：被选中区域的服务，若勾选了相应服务前面的复选框，则表示允许与之相关的流量。<br>13：firewall-config工具的运行状态。</p>
</blockquote>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/firewall-config%E7%95%8C%E9%9D%A2.png" alt="firewall-config的界面"></p>
<p>刘遄老师再啰嗦几句。在使用firewall-config工具配置完防火墙策略之后，无须进行二次确认，因为只要有修改内容，它就自动进行保存。下面进行动手实践环节。</p>
<p>我们先将当前区域中请求http服务的流量设置为允许，但仅限当前生效。具体配置如图8-3所示。</p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E5%85%81%E8%AE%B8%E5%85%B6%E4%BB%96%E4%B8%BB%E6%9C%BA%E8%AE%BF%E9%97%AEhttp%E6%9C%8D%E5%8A%A1.png" alt="放行请求http服务的流量"></p>
<p>尝试添加一条防火墙策略规则，使其放行访问8080～8088端口（TCP协议）的流量，并将其设置为永久生效，以达到系统重启后防火墙策略依然生效的目的。在按照图8-4所示的界面配置完毕之后，还需要在Options菜单中单击Reload Firewalld命令，让配置的防火墙策略立即生效（见图8-5）。这与在命令行中执行–reload参数的效果一样。</p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E5%85%81%E8%AE%B8%E5%85%B6%E4%BB%96%E4%B8%BB%E6%9C%BA%E8%AE%BF%E9%97%AE8080-8088%E7%AB%AF%E5%8F%A3.png" alt="放行访问8080～8088端口的流量"></p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E9%87%8D%E5%90%AF%E5%90%8E%E4%BE%9D%E7%84%B6%E6%9C%89%E6%95%88.png" alt="让配置的防火墙策略规则立即生效"></p>
<p>前面在讲解firewall-config工具的功能时，曾经提到了SNAT（Source Network Address Translation，源网络地址转换）技术。SNAT是一种为了解决IP地址匮乏而设计的技术，它可以使得多个内网中的用户通过同一个外网IP接入Internet。该技术的应用非常广泛，甚至可以说我们每天都在使用，只不过没有察觉到罢了。比如，当我们通过家中的网关设备（比如无线路由器）访问本书配套站点<a href="http://www.linuxprobe.com时，就用到了SNAT技术。" rel="external nofollow noopener noreferrer" target="_blank">www.linuxprobe.com时，就用到了SNAT技术。</a></p>
<p>大家可以看一下在网络中不使用SNAT技术（见图8-6）和使用SNAT技术（见图8-7）时的情况。在图8-6所示的局域网中有多台PC，如果网关服务器没有应用SNAT技术，则互联网中的网站服务器在收到PC的请求数据包，并回送响应数据包时，将无法在网络中找到这个私有网络的IP地址，所以PC也就收不到响应数据包了。在图8-7所示的局域网中，由于网关服务器应用了SNAT技术，所以互联网中的网站服务器会将响应数据包发给网关服务器，再由后者转发给局域网中的PC。</p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E6%9C%AA%E7%94%A8SNAT1.png" alt="没有使用SNAT技术的网络"></p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E4%BD%BF%E7%94%A8SNAT1.png" alt="使用SNAT技术处理过的网络"></p>
<p>使用iptables命令实现SNAT技术是一件很麻烦的事情，但是在firewall-config中却是小菜一碟了。用户只需按照图8-8进行配置，并选中Masquerade zone复选框，就自动开启了SNAT技术。</p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E5%BC%80%E5%90%AF%E4%BC%AA%E8%A3%85%E5%8A%9F%E8%83%BD.png" alt="开启防火墙的SNAT技术"></p>
<p>为了让大家直观查看不同工具在实现相同功能的区别，这里使用firewall-config工具重新演示了前面使用firewall-cmd来配置防火墙策略规则，将本机888端口的流量转发到22端口，且要求当前和长期均有效，具体如图8-9和图8-10所示。</p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E5%B0%86%E5%90%91%E6%9C%AC%E6%9C%BA888%E7%AB%AF%E5%8F%A3%E7%9A%84%E8%AF%B7%E6%B1%82%E8%BD%AC%E5%8F%91%E8%87%B3%E6%9C%AC%E6%9C%BA%E7%9A%8422%E7%AB%AF%E5%8F%A3.png" alt="配置本地的端口转发"></p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/reload%E7%AB%8B%E5%8D%B3%E7%94%9F%E6%95%88.png" alt="让防火墙效策略规则立即生效"></p>
<p>配置富规则，让192.168.10.20主机访问到本机的1234端口号，如图8-11所示。</p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E4%BB%85%E5%85%81%E8%AE%B8192.168.10.20%E4%B8%BB%E6%9C%BA%E8%AE%BF%E9%97%AE%E6%9C%AC%E6%9C%BA%E7%9A%841234%E7%AB%AF%E5%8F%A3.png" alt="配置防火墙富规则策略"></p>
<p>如果生产环境中的服务器有多块网卡在同时提供服务（这种情况很常见），则对内网和对外网提供服务的网卡要选择的防火墙策略区域也是不一样的。也就是说，可以把网卡与防火墙策略区域进行绑定（见图8-12），这样就可以使用不同的防火墙区域策略，对源自不同网卡的流量进行针对性的监控，效果会更好。</p>
<p>最后，刘遄老师想说的是，firewall-config工具真的非常实用，很多原本复杂的长命令被用图形化按钮替代，设置规则也简单明了，足以应对日常工作。所以再次向大家强调配置防火墙策略的原则—只要能实现所需的功能，用什么工具请随君便。</p>
<p><img src="https://melville-images.oss-cn-shanghai.aliyuncs.com/blog/iperf%E5%92%8Cfirewalled%E7%9A%84%E5%8C%BA%E5%88%AB/%E6%9F%A5%E7%9C%8B%E7%BD%91%E5%8D%A1%E8%AE%BE%E5%A4%87%E4%BF%A1%E6%81%AF.png" alt="把网卡与防火墙策略区域进行绑定"></p>
<h1 id="4-服务的访问控制列表"><a href="#4-服务的访问控制列表" class="headerlink" title="4. 服务的访问控制列表"></a>4. 服务的访问控制列表</h1><p>TCP Wrappers是RHEL 7系统中默认启用的一款流量监控程序，它能够根据来访主机的地址与本机的目标服务程序作出允许或拒绝的操作。换句话说，Linux系统中其实有两个层面的防火墙，第一种是前面讲到的基于TCP/IP协议的流量过滤工具，而TCP Wrappers服务则是能允许或禁止Linux系统提供服务的防火墙，从而在更高层面保护了Linux系统的安全运行。</p>
<p>TCP Wrappers服务的防火墙策略由两个控制列表文件所控制，用户可以编辑允许控制列表文件来放行对服务的请求流量，也可以编辑拒绝控制列表文件来阻止对服务的请求流量。控制列表文件修改后会立即生效，系统将会先检查允许控制列表文件（/etc/hosts.allow），如果匹配到相应的允许策略则放行流量；如果没有匹配，则去进一步匹配拒绝控制列表文件（/etc/hosts.deny），若找到匹配项则拒绝该流量。如果这两个文件全都没有匹配到，则默认放行流量。</p>
<p>TCP Wrappers服务的控制列表文件配置起来并不复杂，常用的参数如表4所示。</p>
<p>表4        TCP Wrappers服务的控制列表文件中常用的参数</p>
<table>
<thead>
<tr>
<th style="text-align:left">客户端类型</th>
<th style="text-align:left">示例</th>
<th style="text-align:left">满足示例的客户端列表</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">单一主机</td>
<td style="text-align:left">192.168.10.10</td>
<td style="text-align:left">IP地址为192.168.10.10的主机</td>
</tr>
<tr>
<td style="text-align:left">指定网段</td>
<td style="text-align:left">192.168.10.</td>
<td style="text-align:left">IP段为192.168.10.0/24的主机</td>
</tr>
<tr>
<td style="text-align:left">指定网段</td>
<td style="text-align:left">192.168.10.0/255.255.255.0</td>
<td style="text-align:left">IP段为192.168.10.0/24的主机</td>
</tr>
<tr>
<td style="text-align:left">指定DNS后缀</td>
<td style="text-align:left">.linuxprobe.com</td>
<td style="text-align:left">所有DNS后缀为.linuxprobe.com的主机</td>
</tr>
<tr>
<td style="text-align:left">指定主机名称</td>
<td style="text-align:left"><a href="http://www.linuxprobe.com" rel="external nofollow noopener noreferrer" target="_blank">www.linuxprobe.com</a></td>
<td style="text-align:left">主机名称为<a href="http://www.linuxprobe.com的主机" rel="external nofollow noopener noreferrer" target="_blank">www.linuxprobe.com的主机</a></td>
</tr>
<tr>
<td style="text-align:left">指定所有客户端</td>
<td style="text-align:left">ALL</td>
<td style="text-align:left">所有主机全部包括在内</td>
</tr>
</tbody>
</table>
<p>在配置TCP Wrappers服务时需要遵循两个原则：</p>
<ol>
<li>编写拒绝策略规则时，填写的是服务名称，而非协议名称；</li>
<li>建议先编写拒绝策略规则，再编写允许策略规则，以便直观地看到相应的效果。</li>
</ol>
<p>下面编写拒绝策略规则文件，禁止访问本机sshd服务的所有流量（无须/etc/hosts.deny文件中修改原有的注释信息）：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># vim /etc/hosts.deny</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># hosts.deny This file contains access rules which are used to</span></span><br><span class="line"><span class="comment"># deny connections to network services that either use</span></span><br><span class="line"><span class="comment"># the tcp_wrappers library or that have been</span></span><br><span class="line"><span class="comment"># started through a tcp_wrappers-enabled xinetd.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># The rules in this file can also be set up in</span></span><br><span class="line"><span class="comment"># /etc/hosts.allow with a 'deny' option instead.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># See 'man 5 hosts_options' and 'man 5 hosts_access'</span></span><br><span class="line"><span class="comment"># for information on rule syntax.</span></span><br><span class="line"><span class="comment"># See 'man tcpd' for information on tcp_wrappers</span></span><br><span class="line">sshd:*</span><br><span class="line">[root@linuxprobe ~]<span class="comment"># ssh 192.168.10.10</span></span><br><span class="line">ssh_exchange_identification: <span class="built_in">read</span>: Connection reset by peer</span><br></pre></td></tr></table></figure>
<p>接下来，在允许策略规则文件中添加一条规则，使其放行源自192.168.10.0/24网段，访问本机sshd服务的所有流量。可以看到，服务器立刻就放行了访问sshd服务的流量，效果非常直观：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">[root@linuxprobe ~]<span class="comment"># vim /etc/hosts.allow</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># hosts.allow This file contains access rules which are used to</span></span><br><span class="line"><span class="comment"># allow or deny connections to network services that</span></span><br><span class="line"><span class="comment"># either use the tcp_wrappers library or that have been</span></span><br><span class="line"><span class="comment"># started through a tcp_wrappers-enabled xinetd.</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># See 'man 5 hosts_options' and 'man 5 hosts_access'</span></span><br><span class="line"><span class="comment"># for information on rule syntax.</span></span><br><span class="line"><span class="comment"># See 'man tcpd' for information on tcp_wrappers</span></span><br><span class="line">sshd:192.168.10.</span><br><span class="line"></span><br><span class="line">[root@linuxprobe ~]<span class="comment"># ssh 192.168.10.10</span></span><br><span class="line">The authenticity of host <span class="string">'192.168.10.10 (192.168.10.10)'</span> can<span class="string">'t be established.</span></span><br><span class="line"><span class="string">ECDSA key fingerprint is 70:3b:5d:37:96:7b:2e:a5:28:0d:7e:dc:47:6a:fe:5c.</span></span><br><span class="line"><span class="string">Are you sure you want to continue connecting (yes/no)? yes</span></span><br><span class="line"><span class="string">Warning: Permanently added '</span>192.168.10.10<span class="string">' (ECDSA) to the list of known hosts.</span></span><br><span class="line"><span class="string">root@192.168.10.10'</span>s password: </span><br><span class="line">Last login: Wed May 4 07:56:29 2017</span><br><span class="line">[root@linuxprobe ~]<span class="comment">#</span></span><br></pre></td></tr></table></figure>
<hr>

      
    </div>

    

    
    
    

    
        
    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div></div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Melville 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="Melville 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/linux/" rel="tag"><i class="fa fa-tag"></i> linux</a>
          
            <a href="/tags/网络/" rel="tag"><i class="fa fa-tag"></i> 网络</a>
          
            <a href="/tags/防火墙/" rel="tag"><i class="fa fa-tag"></i> 防火墙</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/a-2018-10-23-09-27-01.html" rel="next" title="Linux下用iperf测试网络时出现unable to connect to server: No route to host">
                <i class="fa fa-chevron-left"></i> Linux下用iperf测试网络时出现unable to connect to server: No route to host
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/a-2019-01-07-17-20-09.html" rel="prev" title="VMwareWorkstation15Pro激活秘钥">
                VMwareWorkstation15Pro激活秘钥 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="Melville">
            
              <p class="site-author-name" itemprop="name">Melville</p>
              <div class="site-description motion-element" itemprop="description">改革春风吹满地</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">20</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">13</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/do-do-do" title="GitHub &rarr; https://github.com/do-do-do" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.weibo.com/3938468211/profile?rightmod=1&wvr=6&mod=personinfo&is_all=1" title="WeiBo &rarr; https://www.weibo.com/3938468211/profile?rightmod=1&wvr=6&mod=personinfo&is_all=1" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-weibo"></i>WeiBo</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="/y.dark.woood@gmail.com" title="E-Mail &rarr; y.dark.woood@gmail.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://twitter.com/Melville_IT_Dog" title="Twitter &rarr; https://twitter.com/Melville_IT_Dog" rel="external nofollow noopener noreferrer" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                </span>
              
            </div>
          

          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-umbrella"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.aqh.space" title="https://www.aqh.space" rel="external nofollow noopener noreferrer" target="_blank">qinghua</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#1-防火墙管理工具"><span class="nav-text">1. 防火墙管理工具</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-iptables"><span class="nav-text">2. iptables</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-策略与规则链"><span class="nav-text">2.1 策略与规则链</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-基本的命令参数"><span class="nav-text">2.2 基本的命令参数</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-firewalled"><span class="nav-text">3. firewalled</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-终端管理工具"><span class="nav-text">3.1 终端管理工具</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-图形管理工具"><span class="nav-text">3.2 图形管理工具</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-服务的访问控制列表"><span class="nav-text">4. 服务的访问控制列表</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Melville</span>

  

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-users"></i>
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>







  






  



  
    
    
  
  <script color="0,0,255" opacity="0.5" zindex="-1" count="99" src="/lib/canvas-nest/canvas-nest.min.js"></script>













  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="/lib/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>




  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  

  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: true,
    notify: true,
    appId: 'pvhiBwpfHOUBspkJ5iEJ5LFw-gzGzoHsz',
    appKey: 'LrKlAVEWOYfv1JwbdQGXAl3K',
    placeholder: '欢迎留言',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn'
  });
</script>




  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  
<script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
